package com.yonyou.component;

import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.search.*;
import com.yonyou.biz.actions.AutoImport1;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;
import java.util.regex.Pattern;

import static com.yonyou.component.DelFileProcess.writeToNonProjectFile;

public class importProcess extends Task.Backgroundable {

    List<String> log = new ArrayList<>();
    private Project project;

    public importProcess(@Nullable Project project, @Nls(capitalization = Nls.Capitalization.Title) @NotNull String title) {
        super(project, title);
        this.project = project;

    }
    public List<PsiJavaFile> getJavaFilesInPackage(Project project, String packageName) {
        List<PsiJavaFile> javaFiles = new ArrayList<>();
        // 使用 JavaPsiFacade 获取指定包路径的 PsiPackage 对象
        JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
        PsiPackage psiPackage = javaPsiFacade.findPackage(packageName);

        if (psiPackage != null) {
            PsiDirectory[] directories = psiPackage.getDirectories();
            for (PsiDirectory directory : directories) {
                // 查找目录下的所有 Java 文件
                javaFiles.addAll(findJavaFilesInDirectory(directory));
            }
        }

        return javaFiles;
    }
    private List<PsiJavaFile> findJavaFilesInDirectory(PsiDirectory directory) {
        List<PsiJavaFile> javaFiles = new ArrayList<>();
        // 遍历目录下的所有文件
        for (PsiFile file : directory.getFiles()) {
            // 如果是 Java 文件，则添加到列表中
            if (file instanceof PsiJavaFile) {
                javaFiles.add((PsiJavaFile)file);
            }
        }
        // 递归处理子目录
        for (PsiDirectory subDirectory : directory.getSubdirectories()) {
            javaFiles.addAll(findJavaFilesInDirectory(subDirectory));
        }
        return javaFiles;
    }
    public void run(@NotNull ProgressIndicator progressIndicator) {
        log.clear();
        // 设置进度条为模糊进度条
        progressIndicator.setIndeterminate(true);
        try {
            // 在一个事务中运行，以便可以撤消更改
            Runnable runnable = () -> {
                String filePath1 = "D:\\usr\\log33s.txt"; // 文件的完整路径
                List<String> log1 = new ArrayList<>();
                // 获取项目中的所有 Java 文件
                List<PsiJavaFile> psiFiles=getJavaFilesInPackage(this.project,"com.yonyoucloud.fi.tlm");
                List<PsiJavaFile> psiFiles1=getJavaFilesInPackage(this.project,"com.yonyoucloud.fi.fusion");
                psiFiles.addAll(psiFiles1);
                for (PsiFile psiFile : psiFiles) {
                    if (psiFile instanceof PsiJavaFile) {
                        log1.add("check java :"+psiFile.getName() );
                        autoImportClasses(project, (PsiJavaFile) psiFile);

                        VirtualFile virtualFile = psiFile.getVirtualFile();
                        if (virtualFile != null) {
                            Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
                            if (document != null) {
                                for(String old :AutoImport1.replace_text.keySet()){
                                    String text = document.getText();
                                    String newTextContent = text.replaceAll(Pattern.quote(old), AutoImport1.replace_text.get(old));
                                    document.setText(newTextContent);
                                }

                            }
                        }

                    }



                }

                //处理其他
                writeToNonProjectFile(filePath1, log1);
            };

            WriteCommandAction.runWriteCommandAction(project, runnable);

            String filePath = "D:\\usr\\log22s.txt"; // 文件的完整路径
            writeToNonProjectFile(filePath, log);

            com.yonyou.ctm.ctmplugin.utils.NotificationUtil.showDialog("提示","导入完成");
            // 开启进度条
            progressIndicator.setIndeterminate(true);
            // 设置进度条为百分百
            progressIndicator.setFraction(1.0);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Collection<PsiFile> findAllJavaFiles(Project project) {
        GlobalSearchScope scope = GlobalSearchScope.projectScope(project);
        final Collection<VirtualFile> files = FileTypeIndex.getFiles(StdFileTypes.JAVA, scope);
        Collection<PsiFile> list =new ArrayList<PsiFile>();
        PsiManager psiManager = PsiManager.getInstance(project);
        for(VirtualFile file :files){
            list.add(psiManager.findFile(file));
        }
        return list;
    }

    private void autoImportClasses(Project project, PsiJavaFile javaFile) {
        PsiImportList importList = javaFile.getImportList();
        if (importList == null) return;

        PsiImportStatementBase[] importStatements = importList.getAllImportStatements();
        PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
        // 获取已导入的类
        for (PsiImportStatementBase importStatement : importStatements) {
            final String qualifiedName = importStatement.getImportReference().getQualifiedName();
            if(AutoImport1.del_ingoing.contains(qualifiedName)){
                continue;
            }
            if( AutoImport1.delSt.keySet().contains(qualifiedName)){

                final PsiClass psiClass1 = AutoImport1.delSt.get(qualifiedName);

                PsiImportStatement newStatement = factory.createImportStatement(psiClass1);
                importList.add(newStatement);
                importStatement.delete();
                log.add("file1 :"+javaFile.getName()+"|| del "+qualifiedName+"|| set :"+psiClass1.getQualifiedName());
            }

            for(String keys :AutoImport1.other.keySet()){
                if(keys.equals(qualifiedName)){
                    final String qualifiedName1 = AutoImport1.other.get(qualifiedName);
                    PsiImportStatement importStatementElement = factory.createImportStatementOnDemand(qualifiedName1);
                    importList.add(importStatementElement);
                    importStatement.delete();
                    log.add("file2 :"+javaFile.getName()+"|| del "+qualifiedName+"|| set :"+qualifiedName1);
                }
            }

            if("com.yonyoucloud.fi.tlm.rule.enums.common".equals(qualifiedName)){
                final PsiImportStatement onDemandImportStatement = importList.findOnDemandImportStatement("com.yonyou.ctp.finance.rule.domain.enums");
                if(onDemandImportStatement==null){
                    PsiImportStatement importStatementElement1 = factory.createImportStatementOnDemand("com.yonyou.ctp.finance.rule.domain.enums");
                    //importList.addBefore(importStatementElement1, importStatementElement);
                    importList.add(importStatementElement1);
                }

            }
            if("com.yonyoucloud.fi.tlm.enums".equals(qualifiedName)){
                final PsiImportStatement onDemandImportStatement1 = importList.findOnDemandImportStatement("com.yonyou.ctp.finance.enums");
                final PsiImportStatement onDemandImportStatement2 = importList.findOnDemandImportStatement("com.yonyou.ctp.finance.enums.rule");
                final PsiImportStatement onDemandImportStatement3 = importList.findOnDemandImportStatement("com.yonyou.ctp.finance.rule.domain.enums");
                if(onDemandImportStatement1==null){
                    PsiImportStatement importStatementElement11 = factory.createImportStatementOnDemand("com.yonyou.ctp.finance.enums");
                    importList.add(importStatementElement11);
                }
                if(onDemandImportStatement2==null){
                    PsiImportStatement importStatementElement12 = factory.createImportStatementOnDemand("com.yonyou.ctp.finance.enums.rule");
                    importList.add(importStatementElement12);
                }

                if(onDemandImportStatement3==null){
                    PsiImportStatement importStatementElement13 = factory.createImportStatementOnDemand("com.yonyou.ctp.finance.rule.domain.enums");
                    importList.add(importStatementElement13);
                }
            }

        }


    }


}
